﻿using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Controls;
using System.Windows;
using System.Windows.Media;

namespace mediaPrime.Controls.FluidKit.Controls
{
    public class FadeTransition : Transition
    {
        private Rectangle _nextRect;
        private Rectangle _prevRect;
        private Grid _rectContainer;

        private void SetupElements()
        {
            _rectContainer = new Grid();
            _rectContainer.ClipToBounds = true;

            _prevRect = new Rectangle();
            _nextRect = new Rectangle();
            
            _rectContainer.Children.Add(_nextRect);
            _rectContainer.Children.Add(_prevRect);

            NameScope scope = GetNameScope();

            scope.RegisterName("PrevElement", _prevRect);
            scope.RegisterName("NextElement", _nextRect);
        }

        public override void Setup(Brush prevBrush, Brush nextBrush)
        {
            SetupElements();

            if (prevBrush.CanFreeze)
                prevBrush.Freeze();
            if (nextBrush.CanFreeze)
                nextBrush.Freeze();

            _prevRect.Fill = prevBrush;
            _nextRect.Fill = nextBrush;
            Owner.AddTransitionElement(_rectContainer);
        }

        public override Storyboard PrepareStoryboard()
        {
            Storyboard animator = (TransitionResources["FadeAnim"] as Storyboard).Clone();
          
            DoubleAnimation nextAnim = animator.Children[0] as DoubleAnimation;
            Storyboard.SetTargetName(nextAnim, "PrevElement");
            nextAnim.Duration = this.Duration;

            nextAnim.From = 1;
            nextAnim.To = 0;

            return animator;
        }
    }
}
